<template>
  <div>
    <a-modal v-drag-modal class="search-wrapper-box-crm" :visible="visibleSplit" title="拆分需求计划" @cancel="close" @ok="handleOk" width="800px">
        <div style="padding:25px;">
          <span style="margin-right: 40px;">
            <a-tag>物料编码</a-tag> {{formdata.inventoryCode}}
          </span>
          <span style="margin-right: 40px;">
            <a-tag>物料名称</a-tag> {{formdata.inventoryName}}
          </span>
          <span>
            <a-tag>规格型号</a-tag> {{formdata.inventorySpecification}}
          </span>
          <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 7,offset:1 }" :wrapper-col="{ span: 17}" style="padding:0;margin-top:10px;">
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="业务计划" >
                            <a-input 
                               v-decorator="[
                                'bussessPlan',
                                { rules: [{ required: true, message: ' ' }] },
                              ]"
                               placeholder="" 
                               disabled />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="提前期" >
                            <a-input 
                            v-decorator="['productionLeadTime',{ rules: [{ required: true, message: ' ' }] },]" 
                            placeholder="" 
                            disabled />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="建议计划数量" >
                            <a-input placeholder="" 
                            v-decorator="[
                          'baseQuantity',
                          { rules: [{ required: true, message: ' ' }] },
                        ]" disabled/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="已下达数量" >
                            <a-input placeholder="" v-decorator="[
                          'releasedQuantity',
                          { rules: [{ required: false, message: ' ' }] },
                        ]" disabled/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
           <div>
            <span class="ivu-form-item-required">开始时间</span>
            <span class="ivu-form-item-required" style="margin-left:160px;margin-right:150px;">结束时间</span>
            <span class="ivu-form-item-required" style="margin-right:60px;">拆分数量</span>
            <!-- <span>重叠天数</span> -->
           </div>
           <div v-for="(item,index) in dataList" :key="index" style="margin-top:10px">
            <a-date-picker  format="YYYY-MM-DD" @change="(data,datastring) =>  onChangeTime(data,datastring,item)" v-model="item.planBeginDate"></a-date-picker>
            <span style="margin-left:40px;margin-right:40px;">
            <a-date-picker  format="YYYY-MM-DD" @change="(data,datastring) =>  onChangeTimeEnd(data,datastring,item)" v-model="item.planEndDate"></a-date-picker>
            </span>
            <span style="margin-right:40px;">
            <a-input-number size="small" v-model="item.baseQuantity"></a-input-number>
            </span>
            <!-- <span style="margin-right:20px;">
            <a-input-number size="small" v-model="item.overLappingDays"></a-input-number>
            </span> -->
            <span class="icon" style="margin-right:20px" v-if="dataList.length-1 === index && residueNum > 0" @click="add"><a-icon type="plus"/></span>
            <span class="icon" v-if="index !== 0" @click="Deleted(index)"><a-icon type="minus"/></span>
           </div>
        </div>          
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import AgForm from '../../components/AgForm/AgForm.vue'
export default {
  components: { AgForm },
  props:['splitData'],
  directives: {
	  'drag-modal'(el, bindings, vnode){
	    Vue.nextTick(() => {
            let { visible, destroyOnClose } = vnode.componentInstance
            // 防止未定义 destroyOnClose 关闭弹窗时dom未被销毁，指令被重复调用
            if (!visible) return
            let modal = el.getElementsByClassName('ant-modal')[0]
            let header = el.getElementsByClassName('ant-modal-header')[0]
            let left = 0
            let top = 0

            // 未定义 destroyOnClose 时，dom未被销毁，关闭弹窗再次打开，弹窗会停留在上一次拖动的位置
            if (!destroyOnClose) {  
                left = modal.left || 0
             top = modal.top || 0
            }
            // top 初始值为 offsetTop
            top = top || modal.offsetTop
            header.onmousedown = e => {
                let startX = e.clientX;
                let startY = e.clientY;
                header.left = header.offsetLeft;
                header.top = header.offsetTop;
                el.onmousemove = event => {
                    let endX = event.clientX;
                    let endY = event.clientY;
                    modal.left = header.left + (endX - startX) + left;
                    modal.top = header.top + (endY - startY) + top;
                    modal.style.left = modal.left + 'px'
                    modal.style.top = modal.top + 'px'
                }
                el.onmouseup = event => {
                    left = modal.left
                    top = modal.top
                    el.onmousemove = null;
                    el.onmouseup = null; 
                    header.releaseCapture && header.releaseCapture();
                }
                header.setCapture && header.setCapture()
            }
	    })
	  }
	},
  data(){
    return{
      visibleSplit:true,
      formdata:{},
      dataList:[],
      form: this.$form.createForm(this),
      residueNum: null, // 剩余数量
    }
  },
  created(){
      this.init(this.splitData)
  },
  methods:{
    init(data) {
      this.formdata = JSON.parse(JSON.stringify(data))
      // this.residueNum = this.formdata.baseQuantity - (this.formdata.releasedQuantity || 0)
      this.residueNum = this.formdata.baseQuantity

      this.$nextTick(() => {
        this.form.setFieldsValue({...data});
        this.dataList.push({
          planBeginDate:this.splitData.planBeginDate,
          planEndDate:this.splitData.planEndDate,
          baseQuantity: this.residueNum,
          overLappingDays:'',    
        })
      })
      // this.$nextTick(() => {
      //   this.form.needDate = this.splitData.productionLeadTime
      // })
    },
    close(){
      // this.visibleSplit=false
      this.$emit("close",false)
    },
    add(){
      this.dataList.push(
          {
            planBeginDate:this.splitData.planBeginDate,
            planEndDate: this.splitData.planEndDate,
            baseQuantity: this.residueNum,
            overLappingDays:'',    
          }
      )
     },
      Deleted(index){
        this.dataList.splice(index,1)
      },
      handleOk(){
        this.dataList.forEach(item=>{
          if(!item.planBeginDate){
            this.$message.warning("开始时间不能为空")
            return
          }
            if(!item.planEndDate){
            this.$message.warning("结束时间不能为空")
            return
          }
            if(!item.baseQuantity){
            this.$message.warning("拆分数量不能为空")
            return
          }  
        })
       
        if(this.residueNum != 0){
          this.$message.warning('拆分的数量不对！')
          return
        }
        // 保留一条原始值
        this.dataList = this.dataList.map((item,index) => {
           return {
            ...this.splitData,
            id:index === 0 ?  this.splitData.id: undefined,
            releasedQuantity: index === 0 ?  this.splitData.releasedQuantity: 0,
            ...item
           }
        })
        console.log( this.dataList ,' this.dataList ')
        this.$emit('splitSubmit', this.dataList )
        // console.log( this.dataList,'dataListdataList')
      },
      onChangeTime(date,dateString,item) {
        item.planBeginDate = dateString;
      },
      onChangeTimeEnd(date,dateString,item) {
        item.planEndDate = dateString;
      },
      
  },
  watch:{
    dataList:{
      deep:true, // 开启深度监听
      handler(){
         let total = this.dataList.reduce((total,curItem) => {
          return total + Number(curItem.baseQuantity)
         },0)
         console.log(total,'total')
        //  this.residueNum = this.formdata.baseQuantity - (this.formdata.releasedQuantity || 0) - total;
        this.residueNum = this.formdata.baseQuantity  - total;
         console.log(this.residueNum,'222222')
      }
    },
  }
}
</script>

<style>
.ivu-form-item-required::before{
  content:"*";
  margin-right: 4px;
  line-height: 1;
  font-family: SimSun;
  font-size: 14px;
  color: #ed4014;
}
.icon{
  cursor: pointer;
}
</style>